/*
 *  Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 *
 *  Licensed under the GNU General Public License v3 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.gnu.org/licenses/gpl-3.0.html
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package metaphor.persistence;

import java.lang.reflect.Method;

/**
 * Uses reflection to determine if the object is new
 * @author Mark Ashworth <javameme@gmail.com>
 * @version 1.0.0
 * @since 1.0.0
 */
public class ReflectionUnsavedValueStrategy implements UnsavedValueStrategy {
    public static final String DEFAULT_METHOD = "getId";
    public static final Object DEFAULT_VALUE = null;
    
    /* The getter method to retrieve the value to test */
    private String method;

    /* The value that represents an unsaved value */
    private Object unsavedValue;

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public Object getUnsavedValue() {
        return unsavedValue;
    }

    public void setUnsavedValue(Object unsavedValue) {
        this.unsavedValue = unsavedValue;
    }

    public boolean isNew(Object object) throws UnsavedValueStrategyException {
        if (object == null) throw new UnsavedValueStrategyException("The object is null");

        try {
            Method m = object.getClass().getMethod(this.method, new Class[]{});
            Object value = m.invoke(object, new Object[]{});
            return value == unsavedValue;
        } catch (Exception e) {
            throw new UnsavedValueStrategyException("Unable to determine if object is new", e);
        }
    }
}
